package com.wisdytech.linkdcs.equipLifeCycle.maintain.action;


import com.wisdytech.common.handler.ResourceMatchingService;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageInfo;
import com.wisdytech.common.bean.Filter;
import com.wisdytech.common.bean.StandardResult;
import com.wisdytech.common.bean.StandardTableResult;
import com.wisdytech.common.utils.BaseUtil;
import com.wisdytech.common.utils.DataTransformUtil;
import com.wisdytech.common.utils.ExcelUtil;
import com.wisdytech.linkdcs.equipLifeCycle.maintain.dto.MaintenanceItemRecordDTO;
import com.wisdytech.linkdcs.equipLifeCycle.maintain.dto.MaintenanceTaskDTO;
import com.wisdytech.linkdcs.equipLifeCycle.maintain.dto.TeskResultDTO;
import com.wisdytech.linkdcs.equipLifeCycle.maintain.model.MaintenanceRecord;
import com.wisdytech.linkdcs.equipLifeCycle.maintain.service.IMaintenanceRecordService;
import com.wisdytech.linkdcs.equipLifeCycle.maintain.service.IMaintenanceTaskService;
import com.wisdytech.linkdcs.equipLifeCycle.maintain.vo.MaintenanceRecordVO;
import com.wisdytech.linkdcs.equipLifeCycle.maintain.vo.TPReplaceTempVO;
import com.wisdytech.linkdcs.equipLifeCycle.malfunction.model.TPReplaceTemp;
import com.wisdytech.linkdcs.equipLifeCycle.malfunction.service.ITPReplaceTempService;
import com.wisdytech.linkdcs.partLife.service.IPartService;
import com.wisdytech.linkdcs.system.model.SysUser;

import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;

/**
 * <p>
 *  保养记录前端控制器
 * </p>
 *
 * @author chenbin
 * @since 2018-06-19
 */
@Controller
@RequestMapping("/maintain/maintenanceRecord")
public class MaintenanceRecordController {

    /**
     * 保养任务service
     */
    @Autowired
    @Qualifier("iMaintenanceTaskService")
    private IMaintenanceTaskService iMaintenanceTaskService;
    @Autowired
    @Qualifier("iTPReplaceTempService")
    private ITPReplaceTempService iTPReplaceTempService;
    @Autowired
    @Qualifier("iPartService")
    private IPartService iPartService;
    @Autowired
    @Qualifier("iMaintenanceRecordService")
    private IMaintenanceRecordService iMaintenanceRecordService;
    @Autowired
    @Qualifier("resourceMatchingService")
    private ResourceMatchingService resourceMatchingService;
	/**
     * 
     * <p>Description: 设备保养计划</p>
     * @param model
     * @return
     */
    @RequestMapping("/index")
    public String maintainItem(Model model,HttpServletRequest httpRequest){
        this.resourceMatchingService.getResourceName(httpRequest,model);
        return "lifeCycle/equipLifeCycle/maintain/taskConfirm";
    }
    
	/**
     * 
     * <p>Description: 设备保养计划</p>
     * @param model
     * @return
     */
    @RequestMapping("/record")
    public String maintainRecord(Model model,HttpServletRequest httpRequest){
        this.resourceMatchingService.getResourceName(httpRequest,model);
        return "lifeCycle/equipLifeCycle/maintain/taskRecord";
    }
    
    
	/**
     * 
     * <p>Description: 设备保养计划</p>
     * @param model
     * @return
     */
    @RequestMapping("/item/record")
    public String maintainItemRecord(Model model,HttpServletRequest httpRequest){
        this.resourceMatchingService.getResourceName(httpRequest,model);
        return "lifeCycle/equipLifeCycle/maintain/itemRecord";
    }
    
    /**
     * 分页条件查询需要确认的保养任务
     * @param taskDTO 查询条件
     * @param filter 分页参数
     * @return 需要确认的保养任务
     * @throws IOException 
     */
    @RequestMapping(value = "/listTaskConfirmByFilter/get.mvc")
    @ResponseBody	
    public StandardTableResult<MaintenanceRecordVO> listTaskConfirmByFilter(MaintenanceTaskDTO taskDTO,Filter filter) throws IOException{
        SysUser userSession = BaseUtil.getCurrentUser();
        String loginName = userSession.getTruename();
        //查询周期计划
    	PageInfo<MaintenanceRecord> tasks =this.iMaintenanceRecordService.listTaskConfirmByFilter(taskDTO,filter,loginName);
        //转换为前台结果集
        List<MaintenanceRecord> list=tasks.getList();
        List<MaintenanceRecordVO> VOList=new ArrayList<MaintenanceRecordVO>();
        for(MaintenanceRecord maintenanceRecord:list){
        	VOList.add(DataTransformUtil.changeTaskRecordVO(maintenanceRecord));
        }
        return new StandardTableResult<MaintenanceRecordVO>(tasks.getTotal(),VOList);
    }
    
    /**
     * <p>Description: 保存保养结果</p> 
     * @param list 处理对象
     * @return 处理结果对象
     */
    @RequestMapping(value = "/saveReplaceTemp/save.mvc")
    @ResponseBody
    public StandardResult saveTeskResult(@RequestBody ArrayList<TeskResultDTO> list) {
    	iMaintenanceRecordService.saveTeskResult(list);
        return StandardResult.getSuccessResult();
    }
    
    /**
     * 分页条件查询保养记录
     * @param taskDTO 备件名称
     * @param filter 分页参数
     * @return 保养记录
     * @throws IOException 
     */
    @RequestMapping(value = "/listTaskRecordByFilter/get.mvc")
    @ResponseBody	
    public StandardTableResult<MaintenanceRecordVO> listTaskRecordByFilter(MaintenanceTaskDTO taskDTO,Filter filter) throws IOException{
        SysUser userSession = BaseUtil.getCurrentUser();
        String loginName = userSession.getTruename();
    	PageInfo<MaintenanceRecord> tasks =this.iMaintenanceRecordService.listTaskRecordByFilter(taskDTO,filter,loginName);
        //转换为前台结果集
        List<MaintenanceRecord> list=tasks.getList();
        List<MaintenanceRecordVO> VOList=new ArrayList<MaintenanceRecordVO>();
        for(MaintenanceRecord maintenanceRecord:list){
        	VOList.add(DataTransformUtil.changeTaskRecordVO(maintenanceRecord));
        }
        return new StandardTableResult<MaintenanceRecordVO>(tasks.getTotal(),VOList);
    }
    
    /**
     * 分页条件查询临时保存的工装及备件记录
     * @param pkId 唯一id
     * @param filter 分页参数
     * @return 临时保存的工装及备件记录
     */
    @RequestMapping(value = "/getRecordTemps/get.mvc")
    @ResponseBody	
    public StandardTableResult<TPReplaceTempVO> getRecordTemps(Filter filter,String pkId) throws IOException{
    	PageInfo<TPReplaceTemp> temps =this.iTPReplaceTempService.getRecordTemps(filter, pkId);
        //转换为前台结果集
        List<TPReplaceTemp> list=temps.getList();
        List<TPReplaceTempVO> VOList=new ArrayList<TPReplaceTempVO>();
        for(TPReplaceTemp tPReplaceTemp:list){
        	VOList.add(DataTransformUtil.changeReplaceTempVO(tPReplaceTemp));
        }
        return new StandardTableResult<TPReplaceTempVO>(temps.getTotal(),VOList);
    }
    
    /**
     * 分页条件查询临时保存的工装及备件记录
     * @param pkId 唯一id
     * @param filter 分页参数
     * @return 临时保存的工装及备件记录
     */
    @RequestMapping(value = "/getRecordTempsByMal/get.mvc")
    @ResponseBody	
    public StandardTableResult<TPReplaceTempVO> getRecordTempsByMal(Filter filter,String pkId) throws IOException{
    	PageInfo<TPReplaceTemp> temps =this.iTPReplaceTempService.getRecordTempsByMal(filter, pkId);
        //转换为前台结果集
        List<TPReplaceTemp> list=temps.getList();
        List<TPReplaceTempVO> VOList=new ArrayList<TPReplaceTempVO>();
        for(TPReplaceTemp tPReplaceTemp:list){
        	VOList.add(DataTransformUtil.changeReplaceTempVO(tPReplaceTemp));
        }
        return new StandardTableResult<TPReplaceTempVO>(temps.getTotal(),VOList);
    }
    
    
    /**
     * <p>Description: 保存保养确认结果</p> 
     * @param list 处理对象
     * @return 处理结果对象
     */
    @RequestMapping(value = "/saveTeskConfirmResult/save.mvc")
    @ResponseBody
    public StandardResult saveTeskConfirmResult(String confirmResult,String pkId) {
    	iMaintenanceRecordService.saveTeskConfirmResult(confirmResult,pkId);
        return StandardResult.getSuccessResult();
    }
    
    
    /**
     * 导出保养查询页面的数据信息
     * @param request 
     * @param response
     * @param filter
     * @throws Exception
     */
     @RequestMapping(value = "/exportTaskRecord/export.mvc")
     @ResponseBody
     public void exportTaskRecord(HttpServletRequest request, HttpServletResponse response, Filter filter) throws Exception {
         SimpleDateFormat dateFormat;
         dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
         String[] columnNames = null;
         String[] fileNames = null;
         String fileName = "保养信息";
         String equipCode = request.getParameter("equipCode");
         if("null".equals(equipCode)) {
        	 equipCode="";
         }
         String equipName = request.getParameter("equipName");
         if("null".equals(equipName)) {
        	 equipName="";
         }
         String supplier = request.getParameter("supplier");
         if("null".equals(supplier)) {
        	 supplier="";
         }
         String modelType = request.getParameter("modelType");
         if("null".equals(modelType)) {
        	 modelType="";
         }
         String startTime = request.getParameter("startTime");
         if("null".equals(startTime)) {
        	 startTime="";
         }
         String endTime = request.getParameter("endTime");
         if("null".equals(endTime)) {
        	 endTime="";
         }
         String maintainCycle = request.getParameter("maintainCycle");
         if("null".equals(maintainCycle)) {
        	 maintainCycle="";
         }
         MaintenanceTaskDTO taskDTO = new MaintenanceTaskDTO();
         taskDTO.setEndTime(endTime);
         taskDTO.setEquipCode(equipCode);
         taskDTO.setEquipName(equipName);
         if((!maintainCycle.equals(null))&& maintainCycle!="") {
             if("null".equals(maintainCycle)) {
            	 taskDTO.setMaintainCycle(Double.parseDouble(maintainCycle));
             }
         }
         if(!"undefined".equals(modelType) && !"null".equals(modelType)) {
        	 taskDTO.setModelType(modelType);
         }
         taskDTO.setStartTime(startTime);
         taskDTO.setSupplier(supplier);
         SysUser userSession = BaseUtil.getCurrentUser();
         String loginName = userSession.getTruename();
         filter.setSize(65535);
//         filter.setNum(0);
         PageInfo<MaintenanceRecord> tasks =this.iMaintenanceRecordService.listTaskRecordByFilter(taskDTO,filter,loginName);
         List<MaintenanceRecord> list=tasks.getList();
//         for (MaintenanceRecord maintenanceRecord : list) {
//             if (maintenanceRecord.getStatus()==0.0) {
//            	 maintenanceRecord.setStatus();
//             }else {
//            	 maintenanceRecord.setType("已完成");
//             }
//             if (maintenanceRecord.getConfirmResult()==0.0) {
//            	 maintenanceRecord.setType("合肥");
//             }else {
//            	 maintenanceRecord.setType("已完成");
//             }
//         }
         for(MaintenanceRecord record : list) {
        	 if(record.getModelType().equals("1")) {
        		 record.setModelType("生产类");
        	 }
        	 if(record.getModelType().equals("2")) {
        		 record.setModelType("环境类");
        	 }
        	 if(record.getModelType().equals("3")) {
        		 record.setModelType("能源类");
        	 }
        	 if(record.getModelType().equals("4")) {
        		 record.setModelType("检测类");
        	 }
        	 if(record.getModelType().equals("5")) {
        		 record.setModelType("生产辅助类");
        	 }
        	 if(record.getStatus()==1) {
        		 record.setTaskStatus("已完成");
        	 }
        	 if(record.getStatus()==0) {
        		 record.setTaskStatus("待确认");
        	 }

        	 if(record.getStatus()==0) {
        		 record.setTaskStatus("待确认");
        	 }
         }
         String finalFileName = null;  
         final String userAgent = request.getHeader("USER-AGENT"); 
         if(StringUtils.contains(userAgent, "MSIE")){
             //IE浏览器  
             finalFileName = URLEncoder.encode(fileName,"UTF8");  
         }else {
             finalFileName = fileName;
         }
         columnNames = new String[] { "保养状态", "设备类别", "设备编号", "设备名称", "供应商", "保养类别编码", "厂区","产线","车间","区域","保养周期（天）","保养时间","保养人","确认结果","确认时间","确认人"};
         fileNames = new String[] { "TaskStatus", "modelType", "equipCode","equipName","supplier", "typeCode", "factoryName","lineName","shopName","areaName","maintainCycle","createDate","createUser","confirmResult","confirmDate","confirmUser"};
         ExcelUtil.exportExcel(response, list, MaintenanceRecord.class, columnNames, fileNames,
                 finalFileName + dateFormat.format(new Date()));
     }
     
     
     /**
      * 分页条件查询保养项记录
      * @param taskDTO 备件名称
      * @param filter 分页参数
      * @return 保养记录
      * @throws IOException 
      */
     @RequestMapping(value = "/listItemRecordByFilter/get.mvc")
     @ResponseBody	
     public StandardTableResult<MaintenanceRecord> listItemRecordByFilter(MaintenanceItemRecordDTO itemDTO,Filter filter) throws IOException{
     	PageInfo<MaintenanceRecord> tasks =this.iMaintenanceRecordService.listItemRecordByFilter(itemDTO,filter);
         //转换为前台结果集
         List<MaintenanceRecord> list=tasks.getList();
         return new StandardTableResult<MaintenanceRecord>(tasks.getTotal(),list);
     }
     
     
     /**
      * 导出保养查询页面的数据信息
      * @param request 
      * @param response
      * @param filter
      * @throws Exception
      */
      @RequestMapping(value = "/exportItemRecord/export.mvc")
      @ResponseBody
      public void exportItemRecord(HttpServletRequest request, HttpServletResponse response, Filter filter) throws Exception {
          SimpleDateFormat dateFormat;
          dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
          String[] columnNames = null;
          String[] fileNames = null;
          String fileName = "保养信息";
          String equipCode = request.getParameter("equipCode");
          if("null".equals(equipCode)) {
         	 equipCode="";
          }
          String equipName = request.getParameter("equipName");
          if("null".equals(equipName)) {
         	 equipName="";
          }
          String typeName = request.getParameter("typeName");
          if("null".equals(typeName)) {
        	  typeName="";
          }
          String itemName = request.getParameter("itemName");
          if("null".equals(itemName)) {
        	  itemName="";
          }
          String startTime = request.getParameter("startTime");
          if("null".equals(startTime)) {
         	 startTime="";
          }
          String endTime = request.getParameter("endTime");
          if("null".equals(endTime)) {
         	 endTime="";
          }
          MaintenanceItemRecordDTO taskDTO = new MaintenanceItemRecordDTO();
          taskDTO.setEndTime(endTime);
          taskDTO.setEquipCode(equipCode);
          taskDTO.setEquipName(equipName);
          taskDTO.setStartTime(startTime);
          taskDTO.setTypeName(typeName);
          taskDTO.setItemName(itemName);
          SysUser userSession = BaseUtil.getCurrentUser();
          String loginName = userSession.getTruename();
          filter.setSize(65535);
          PageInfo<MaintenanceRecord> tasks =this.iMaintenanceRecordService.listItemRecordByFilter(taskDTO,filter);
          //转换为前台结果集
          List<MaintenanceRecord> list=tasks.getList();
          for(MaintenanceRecord record : list) {
         	 if(record.getStopItem().equals("0")) {
         		 record.setStopItem("是");
         	 }
         	 if(record.getStopItem().equals("1")) {
         		 record.setStopItem("否");
         	 }
         	 if(record.getQualityItem().equals("0")) {
         		 record.setQualityItem("是");
         	 }
         	 if(record.getQualityItem().equals("1")) {
         		 record.setQualityItem("否");
         	 }
         	 if(record.getMaintenanceResult().equals("0")) {
         		 record.setMaintenanceResult("已保养");
         	 }
         	 if(record.getMaintenanceResult().equals("1")) {
         		 record.setMaintenanceResult("未保养");
         	 }
          }
          String finalFileName = null;  
          final String userAgent = request.getHeader("USER-AGENT"); 
          if(StringUtils.contains(userAgent, "MSIE")){
              //IE浏览器  
              finalFileName = URLEncoder.encode(fileName,"UTF8");  
          }else {
              finalFileName = fileName;
          }
          columnNames = new String[] {"设备编号", "设备名称", "设备类别编号", "保养类别名称", "保养项编号","保养项名称","保养方法","停机项","品质项","保养时间","保养人","保养结果"};
          fileNames = new String[] {"equipCode","equipName","typeCode", "typeName", "itemCode","itemName","maintenanceMethod","stopItem","qualityItem","createDate","maintainUserName","maintenanceResult"};
          ExcelUtil.exportExcel(response, list, MaintenanceRecord.class, columnNames, fileNames,
                  finalFileName + dateFormat.format(new Date()));
      }
}

